<?php

namespace app\api\controller;

use app\admin\model\Goods as GoodsModel;
use app\admin\model\Cart as CartModel;
use app\common\controller\Api;
use think\Config;
use think\Env;
use think\Log;
use think\Validate;

/**
 * 购物车接口
 */
class Cart extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];
    public function _initialize(){
        parent::_initialize();

        $this->Goods = new GoodsModel;
        $this->CartModel = new CartModel;
    }
    /**
     * 购物车列表
     */
    public function index()
    {
        $user = $this->auth->getUser();
        $goods = $this->Goods
            ->with(['cart']);
        $ids = request()->param('ids');
        $goods = $this->cart($goods,$user,$ids);
        $limit = request()->param('limit',20);
        $goods = $goods->order('createtime','desc')->paginate($limit);
        $earnest = Config::get('site.earnest');
        $buyer_commission = Config::get('site.buyer_commission');
        $this->success('请求成功',[
            'cart'=>$goods,
            'earnest'=>$earnest,//买家定金比例
            'buyer_commission'=>$buyer_commission//买家抽成比例
        ]);
    }
    /**
     * 购物车
     * @return void
     */
    public function cart($goods,$user,$ids)
    {
        if($ids && $ids != ''){
            $ids = explode(',',$ids);
            $collect = db('cart')
                ->whereIn('id',$ids)
                ->where('user_id',$user->id)
                ->field('id,good_id,user_id')
                ->select();
        }else{
            $collect = db('cart')->where('user_id',$user->id)->field('id,good_id,user_id')->select();
        }

        $arr = [];
        if(!empty($collect)){
            foreach ($collect as $v){
                array_push($arr,$v['good_id']);
            }
        }
        $goods = $goods->whereIn('id',$arr);
        return $goods;
    }

    /**
     * 添加购物车
     * @return void
     */
    public function add()
    {
        $user = $this->auth->getUser();
        $goods_id = request()->param('goods_id');
        if(!$goods_id){
            $this->error('参数不全');
        }
        $goods = $this->Goods->where('id',$goods_id)->find();
        if(!$goods || $goods['status'] != 1){
            $this->error('商品已售完或下架');
        }
        $collect = $this->CartModel->where(['user_id'=>$user->id,'good_id'=>$goods_id])->find();
        if($collect){
            $this->success('成功');
        }
        $this->CartModel->insert([
            'user_id'=>$user->id,
            'good_id'=>$goods_id
        ]);
        $this->success('成功');
    }

    /**
     * 删除购物车
     * @return void
     */
    public function del()
    {
        $user = $this->auth->getUser();
        $data = request()->param();
        if(!$data['cart_id']){
            $this->error('参数错误');
        }
        $cart = $this->CartModel->whereIn('id',$data['cart_id'])->delete();
        if($cart){
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }
}
